package patrol.mobile.com.mobilepatrol.activity.toll;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.VideoPlayActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.TrafficChargeDetailBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;

import static patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity.IMAGE_ITEM_ADD;

public class TrafficChargeDetailActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.tv_danwei)
    TextView tvDanwei;
    @BindView(R.id.tv_riqi)
    TextView tvRiqi;
    @BindView(R.id.tv_shangbaoren)
    TextView tvShangbaoren;
    @BindView(R.id.et_tongxingfeiyong)
    EditText etTongxingfeiyong;
    @BindView(R.id.tv_lvse_cheliang)
    EditText tvLvseCheliang;
    @BindView(R.id.tv_lvse_feiyong)
    EditText tvLvseFeiyong;
    @BindView(R.id.tv_rukou)
    EditText tvRukou;
    @BindView(R.id.tv_chukou)
    EditText tvChukou;
    @BindView(R.id.tv_heji)
    TextView tvHeji;
    @BindView(R.id.tv_teshu_shuoming)
    EditText tvTeshuShuoming;
    @BindView(R.id.btn_sure)
    Button btnSure;
    @BindView(R.id.tv_teshu)
    TextView tvTeshu; @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    ArrayList<ImageItem> images = null;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_VSELECT = 102;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private String videoPath = "";
    private HashMap<String, String> idDateBmnameMap;
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_traffic_charge_detail;
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(TrafficChargeDetailActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("交通量收费额明细");
    }
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }
    @Override
    public void initData() {
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        super.initData();
        String id = getIntent().getStringExtra("id");
        if (id == null) return;
        HttpSender sender = new HttpSender(this, baseUrl, Urls.GET_ORG_TRAFFIC_TOLL_DETAIL_ENTITY);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                TrafficChargeDetailBean bean = GsonUtil.GsonToBean(response, TrafficChargeDetailBean.class);
                tvDanwei.setText(bean.getOrgName());
                tvRiqi.setText(bean.getUpDate());
                tvShangbaoren.setText(bean.getUpUserName());
                etTongxingfeiyong.setText(bean.getToll() + "");
                tvLvseCheliang.setText(bean.getGreenDerateCat()+"");
                tvLvseFeiyong.setText(bean.getGreenDerateToll() + "");
                tvRukou.setText(bean.getEntrance() + "");
                tvChukou.setText(bean.getExitus() + "");
                tvHeji.setText(bean.getTotal() + "");
                tvTeshu.setText(bean.getCases());
                tvTeshuShuoming.setText(bean.getDescribes());

                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(TrafficChargeDetailActivity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });

            }
        });
    }

    @Override
    public void setListener() {

    }
    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:

                break;
            default:
                if (TextUtils.isEmpty(adapter.getImages().get(position).mimeType)||adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }

                break;
        }
    }
    @OnClick(R.id.btn_sure)
    public void onViewClicked() {
        finish();
    }

}
